import React, { useCallback } from 'react';
import { Form, Card, Button, Tag, message, Modal, Icon, Checkbox, Spin } from 'antd';
import { history } from 'umi'
import { get as getPath } from 'object-path';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import authHelper from '@/utils/auth/helper';

import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { GroupLabel } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import { fetchManageList } from '@/pages/Setting/Privilege/services';
import { useRequest } from '@/hooks';
import { getDutyDetail2, postChangeDeleteCheck, delectDuty } from '../services';
import { AUDIT } from '../constant';
import styles from './index.less';

const { confirm } = Modal;
const { checkCode } = authHelper;
// 获取详情数据
const PostDetail = ({ location }) => {
    const { query } = location;
    const [loading, setLoading] = React.useState(false);
    const [info, setInfo] = React.useState({});

    const getDetail = async () => {
        setLoading(true);
        const params = { dutyCode: query?.dutyCode };
        const res = await getDutyDetail2(params);

        setLoading(false);
        const { data, code, msg } = res;
        if (code === 10000) {
            setInfo(data);
        } else {
            message.error(msg);
        }
    };
    // 获取权限模板列表
    const { data: manageList, run } = useRequest(fetchManageList, {
        manual: true
    });
    React.useEffect(() => {
        getDetail();
        run();
    }, []);

    const renderStatus = () => {
        switch (info?.auditStatus) {
            case 0:
                return <Tag>未审批</Tag>;
            case 1:
                return <Tag color="orange">审批中</Tag>;
            case 2:
                return <Tag color="green">审批通过</Tag>;
            case 3:
                return <Tag color="red">审批驳回</Tag>;
            default:
                return <span>-</span>;
        }
    };
    const baseInfo = [
        {
            key: '所属机构',
            value: info?.organizationName
        },
        {
            key: '岗位名称(中文)',
            value: info?.dutyAlias
        },
        {
            key: '岗位名称(英文)',
            value: info?.dutyAliasEnglish
        },
        {
            key: '是否主管',
            value: info?.leaderPositionFlag === 0 ? '否' : '是'
        },
        {
            key: '审批状态',
            value: renderStatus()
        },
        {
            key: '岗位职责(中文)',
            value: info?.dutyDesc
        },
        {
            key: '岗位职责(英文)',
            value: info?.dutyDescEnglish
        }
    ];

    const renderBlock = arr =>
        arr.map(item => (
            <Form.Item label={item.key} key={item.key} style={{ margin: 0 }}>
                <div style={{ wordBreak: 'break-all' }}>{item.value}</div>
            </Form.Item>
        ));

    const handleOk = useCallback(async dutyCode => {
        // 删除前校验
        const { msg, code: delCheckCode } = await postChangeDeleteCheck(dutyCode);
        if (delCheckCode === 10000) {
            const params = {
                dutyCode,
                operationType: 2
            };
            const { code, data: id, msg: subMsg } = await delectDuty(params);

            if (code === 10000) {
                // 流程不存在提示
                const { workFlowUrl, workFlowErrorMsg } = await hasWorkFlowByType('PostChange', false);
                if (!workFlowUrl) {
                    Modal.error({
                        title: '删除失败',
                        icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                        content: workFlowErrorMsg,
                        okText: '我知道了'
                    });
                    return;
                }

                history.push(`${workFlowUrl}${id}`);
            } else {
                message.error(subMsg);
            }
        } else {
            Modal.error({
                title: '删除失败',
                icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                content: msg,
                okText: '我知道了'
            });
        }
    }, []);
    return (
        <PageHeaderWrapper>
            <Card
                title={
                    <>
                        岗位信息
                        {getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2 && (
                            <Tag color="orange" style={{ marginLeft: 10 }}>
                                {AUDIT[getPath(info, 'auditStatus', '')]}
                            </Tag>
                        )}
                    </>
                }
                bordered={false}
                loading={loading}
                extra={
                    <Spin spinning={loading}>
                        {checkCode('office:orgs:organization:duty:edit') && (
                            <Button
                                type="primary"
                                disabled={info?.auditStatus !== 2 || query?.organizationPermissions === 0}
                                className={styles.btn}
                                onClick={async () => {
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/postedit',
                                        query: {
                                            organizationCode: query && query.organizationCode,
                                            organizationPath: query && query.organizationPath,
                                            organizationName: query && query.organizationName,
                                            dutyCode: query && query.dutyCode
                                        }
                                    });
                                }}
                            >
                                编辑
                            </Button>
                        )}
                        {checkCode('office:orgs:organization:duty:recruit') && (
                            <Button
                                disabled={info?.auditStatus !== 2 || query?.organizationPermissions === 0}
                                className={styles.btn}
                                onClick={async () => {
                                    history.push({
                                        pathname: '/office/personnelManagement/recruitment/demand/apply',
                                        query: {
                                            dutyCode: query.dutyCode,
                                            organizationCode: query.organizationCode
                                        }
                                    });
                                }}
                            >
                                招聘需求
                            </Button>
                        )}
                        {checkCode('office:orgs:organization:duty:delete') && (
                            <Button
                                className={styles.btn}
                                disabled={info?.auditStatus !== 2 || query?.organizationPermissions === 0}
                                onClick={async () => {
                                    const confirmModal = confirm({
                                        title: '确定删除？',
                                        icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                                        okButtonProps: {
                                            disabled: true
                                        },
                                        content: (
                                            <div className={styles.deleteInfo}>
                                                <p>删除此岗位前请先做确认：</p>
                                                <p>· 此岗位是否有在职员工？</p>
                                                <p>· 此岗位是否正在进行招聘？</p>
                                                <p>· 此岗位是否有正在入职的员工？</p>
                                                <p>上述情况皆无，才能够删除此岗位</p>
                                                <div>
                                                    <Checkbox
                                                        onChange={e => {
                                                            confirmModal.update({
                                                                okButtonProps: {
                                                                    disabled: !e.target.checked
                                                                }
                                                            });
                                                        }}
                                                    >
                                                        确认删除该岗位
                                                    </Checkbox>
                                                </div>
                                            </div>
                                        ),
                                        okText: '确定',
                                        cancelText: '取消',
                                        onOk: () => handleOk(query?.dutyCode)
                                    });
                                }}
                            >
                                删除
                            </Button>
                        )}
                    </Spin>
                }
            >
                <Form className={styles.formWrap}>
                    <>
                        {renderBlock(baseInfo)}
                        <Form.Item label="权限模板">
                            <GroupLabel
                                data={manageList?.data}
                                title="权限模板"
                                value={info?.roleCodeList}
                                placeholder="请选择"
                                style={{ display: 'inline-block' }}
                            />
                        </Form.Item>
                    </>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default PostDetail;
